﻿using System;

namespace Sencha.Serialization.Exceptions
{
	[Serializable]
	sealed class UnexpectedToken : JsonSerializationException
	{
		public UnexpectedToken(IJsonReader reader, params JsonToken[] expectedTokens) :
			base(Loc.GetErrorString("Exception_UnexpectedToken", reader.IsEndOfStream() ? JsonToken.EndOfStream : reader.Token, JoinTokens(expectedTokens)), ErrorCode.UnexpectedToken, reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");
			if (expectedTokens == null)
				throw new ArgumentNullException("expectedTokens");
			System.Diagnostics.Contracts.Contract.EndContractBlock();
		}
		protected UnexpectedToken(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
			: base(info, context)
		{
		}

		private static object JoinTokens(JsonToken[] expectedTokens)
		{
			if (expectedTokens == null)
				throw new ArgumentNullException("expectedTokens");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			if (expectedTokens.Length == 0)
				return "<no tokens>";
#if NET40
			return String.Join(", ", expectedTokens);
#else
			var tokens = Array.ConvertAll(expectedTokens, c => c.ToString());
			return String.Join(", ", tokens);
#endif
		}
	}
}
